package com.sinopec.basemodule.utils.kotlin

import com.sinopec.basemodule.BaseApplication
import com.sinopec.basemodule.base.AppManager
import com.sinopec.basemodule.http.ExceptionEngine
import com.sinopec.basemodule.http.api.HttpResult
import com.sinopec.basemodule.http.func.ServerResponseFunc
import com.sinopec.basemodule.utils.ARouterManagerUtils
import com.sinopec.basemodule.utils.ToastUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

object API {
    data class Result<T>(val model: T? = null, val errcode: Int = 0, val errmsg: String = "") {
        val success: Boolean
            get() {
                return errcode == 0 && model != null
            }
    }

    fun <T : Any> request(
        request: Observable<HttpResult<T>>
    ): Observable<Result<T>> {
        return request
            .compose { it ->
                it
                    .map(ServerResponseFunc())
                    .map { Result(model = it) }
                    .onErrorResumeNext { throwable: Throwable ->
                        val err = ExceptionEngine.handleException(throwable)
                        val rst = Result<T>(errcode = err.code, errmsg = err.message ?: "未知异常")
                        Observable.just(rst)
                    }
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .filter {
                        if ((4001..4008).contains(it.errcode)) {
                            //token失效
                            ToastUtils.showToast("登录信息过期，请重新登录！")
                            //关闭所有的activity
                            AppManager.getInstance().finishAllActivity()
                            BaseApplication.getInstance().exit()
                            ARouterManagerUtils.gotoLoginActivity()

                            false
                        } else {

                            true
                        }
                    }
            }
    }
}